<template>
  <div>
    <el-card class="search-card">
      <BasicForm
        ref="basicForm"
        formItemWidth="130px"
        :formColumns="formItems"
        :dataSource="formData"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
      />
    </el-card>
    <el-card class="table-card">
      <skus-table
        ref="skusTable"
        showSelectCol
        showActionCol
        :showPagination="isShowPagination"
        :tableHeight="480"
        :dataSource="tableInfo.list"
        :columns="tableInfo.columns"
        :loading="tableInfo.loading"
        :pageSizes="pageSizes"
        :pagination="pagination"
        :total="pagination.total"
        :selectionChange="handleSelectionChange"
        :checkSelectable="checkSelectable"
        :actionRender="renderTableBtnAction"
        @pageChange="handlePageChange"
        @pageSizeSelect="handlePageSizeChange"
      >
        <div slot="content_context">
          <!-- 按钮操作栏 -->
          <BtnRender :render="renderBtnsBar" />
        </div>
      </skus-table>
    </el-card>
    <!-- 库存数量查看弹框 -->
    <StockNumDialog
      ref="stockNum"
      :visible.sync="stockNum.visible"
      :stockKey="stockNum.stockKey"
    />
    <!-- 选择替代商品弹框 -->
    <SelectReplaceProductDialog
      :visible.sync="selectReplaceProduct.visible"
      :product-kind="selectReplaceProduct.productKind"
      @getResults="getSelectedReplaceProduct"
    />
    <!-- 高级关联 - 下架弹框 -->
    <ReplaceProductSeniorDialog
      ref="replaceSenior"
      :visible.sync="seniorLinkedDown.visible"
      @seniorSearchResult="getTableDataBySeniorDown"
    />
    <!-- 高级关联 - 上架弹框 -->
    <SeniorLinkedDialog
      :visible.sync="seniorLinkedUp.visible"
      :columns="seniorLinkedUp.columns"
      :dataSource="seniorLinkedUp.dataSource"
      @seniorSearchResult="getTableDataBySeniorUp"
    />
    <!-- 提交原因- 上架弹框 -->
    <InputReasonDialog
      ref="reasonRef"
      :visible.sync="batchUp.visible"
      :submitLoading="batchUp.loading"
      :handleSubmit="batchSubmitUpSkuInfo"
    />
    <!-- 提交原因- 下架弹框 -->
    <StopOrDownSubmittedDialog
      :submitLoading="batchDown.loading"
      :visible.sync="batchDown.visible"
      :handleSubmit="batchSubmitDownSkuInfo"
      :hasSales="hasSales"
    />
    <!-- 历史记录查询弹框 -->
    <ShowListDialog
      :visible.sync="showList.visible"
      :dialogTitle="showList.title"
      :tableLoading="showList.loading"
      :tableColumns="showList.columns"
      :tableData="showList.list"
    />
  </div>
</template>
<script>
import BasicForm from '@/components/BasicForm';
import SkusTable from '@/components/skusTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import ShowListDialog from '@/components/ShowListDialog';
import InputReasonDialog from '@/components/InputReasonDialog';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import StockNumDialog from '@/pages/commodity/components/StockNumDialog';
import SelectReplaceProductDialog from '@/pages/commodity/components/SelectReplaceProductDialog';
import ReplaceProductSeniorDialog from '@/pages/commodity/components/ReplaceProductSeniorDialog';
import StopOrDownSubmittedDialog from '@/pages/commodity/components/StopOrDownSubmittedDialog';
import skusPage from '@/mixins/commodity/skusPage';
import { getBtnsBar, getTableAction } from '@/utils/getBtnsRender';
import { setAuthBtnId } from '@/utils/bizUtils';
import { getInitFormData } from '@/utils/getUtils';
import { FORM_ITEMS, getTableColumns } from './constants/toHandle';
import { HISTORY_LIST_COLUMNS } from './constants';
import {
  getHandlingListService,
  searchSeniorLinkedDownService,
  searchSeniorLinkedUpService,
  submitDownInfoService,
  submitUpInfoService,
  getHistoryRecordsService
} from '@/api/commodity/commodityManage/upOrDownManage';
import { manageAreaSearchService } from '@/api/public';
export default {
  mixins: [skusPage],
  components: {
    BasicForm,
    SkusTable,
    BtnRender,
    StockNumDialog,
    ShowListDialog,
    InputReasonDialog,
    SeniorLinkedDialog,
    SelectReplaceProductDialog,
    ReplaceProductSeniorDialog,
    StopOrDownSubmittedDialog,
  },
  data () {
    return {
      formItems: FORM_ITEMS,
      formData: getInitFormData(FORM_ITEMS),
      // 表格信息
      tableInfo: {
        list: [],
        columns: [],
        selection: [],
        loading: false
      },
      // 库存数量弹框
      stockNum: {
        visible: false,
        stockKey: ''
      },
      // 选择替代商品弹框
      selectReplaceProduct: {
        visible: false,
        productKind: '',
        selectIndex: -1
      },
      // 高级关联 - 下架
      seniorLinkedDown: {
        visible: false,
        relParamList: [], // 查询结果
      },
      // 高级关联 - 上架
      seniorLinkedUp: {
        visible: false,
        columns: [{ label: 'SKU编码', prop: 'skuNo', type: 'textarea' }],
        dataSource: [{ skuNo: '' }]
      },
      // 批量上架
      batchUp: {
        visible: false,
        loading: false
      },
      // 批量下架
      batchDown: {
        visible: false,
        loading: false
      },
      showList: {
        visible: false,
        title: '历史上下架记录',
        loading: false,
        columns: HISTORY_LIST_COLUMNS,
        list: []
      },
      isShowPagination: true, // 是否展示分页，默认展示
      waitParams: null // 代办参数
    }
  },
  mounted () {
    this.setAreaOptions()
    this.tableInfo.columns = getTableColumns({
      handleViewStockInfo: this.handleViewStockInfo,
      handleSelectReplaceProduct: this.handleSelectReplaceProduct
    });
    this.runWaitItems()
  },
  computed: {
    // 没有表格勾选
    hasNoSelection () {
      return this.tableInfo.selection.length === 0;
    },
    // 展示批量下架按钮栏
    isShowDownBtnsBar () {
      const isEmptyTable = this.tableInfo.list.length === 0;
      if (isEmptyTable) return true;
      const isShowUpSku = this.tableInfo.list[0].state === '1';
      return isShowUpSku; // 当前展示上架时，展示下架按钮，反之展示上架按钮
    },
    hasSales () {
      return this.tableInfo.selection.some(item => item.sales > 0);
    }
  },
  methods: {
    runWaitItems () {
      const { offsetDays } = this.$route.query;
      if (offsetDays) {
        this.waitParams = { offsetDays };
        this.formItems[0].disabled = true;
        this.formData.state = '2';
        this.getTableData();
      }
    },
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      // 批量上架按钮栏
      const upBtnsBar = [
        {
          label: '批量上架',
          method: this.handleBatchUp,
          disabled: this.hasNoSelection,
          icon: 'el-icon-open'
        },
        {
          label: '高级关联-上架',
          method: this.handleSeniorLinkByUp,
          icon: 'el-icon-open'
        }
      ];
      // 批量下架按钮栏
      const downBtnsBar = [
        {
          label: '批量下架',
          method: this.handleBatchDown,
          disabled: this.hasNoSelection,
          icon: 'el-icon-turn-off'
        },
        {
          label: '高级关联-下架',
          method: this.handleSeniorLinkByDown,
          icon: 'el-icon-turn-off'
        }
      ];
      const btnsBar = this.isShowDownBtnsBar ? downBtnsBar : upBtnsBar;
      // 按钮通用属性填充
      const finalBars = btnsBar.map(item => ({
        ...item, type: 'primary', size: 'mini', hasAuth: true
      }));
      return getBtnsBar(h, finalBars, this.showBtn, 'start');
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const actionList = [{ label: '查看历史记录', method: this.handleViewHistoryRecord }];
      return getTableAction({ h, row, actionList })
    },
    // 根据审核状态禁用表格勾选 - 审核中不可勾选
    checkSelectable ({ row }) {
      return row.auditState !== 'AUDITING';
    },
    // 表格勾选
    handleSelectionChange (list) {
      this.tableInfo.selection = list;
    },
    // 批量上架
    handleBatchUp () {
      this.batchUp.visible = true;
    },
    // 批量下架
    handleBatchDown () {
      this.batchDown.visible = true;
    },
    // 高级关联-上架
    handleSeniorLinkByUp () {
      this.seniorLinkedUp.visible = true;
    },
    // 高级关联-下架
    handleSeniorLinkByDown () {
      this.seniorLinkedDown.visible = true;
    },
    // 查看库存信息
    handleViewStockInfo ({ row, key }) {
      this.stockNum.visible = true;
      this.stockNum.stockKey = key;
      this.$nextTick(() => {
        this.$refs.stockNum.getSearchParams({ skuNo: row.skuNo });
      });
    },
    // 选择替代商品
    handleSelectReplaceProduct ({ index }) {
      this.selectReplaceProduct.visible = true;
      this.selectReplaceProduct.productKind = this.formData.productKind
      this.selectReplaceProduct.selectIndex = index;
    },
    // 查看历史记录
    handleViewHistoryRecord (row) {
      this.showList.visible = true;
      this.getTableDataByHistoryRecord(row.skuNo);
    },
    // 获取选择的替代商品信息
    getSelectedReplaceProduct (data) {
      const index = this.selectReplaceProduct.selectIndex;
      if (index === -1) return false;
      const isSelectSelf = data.skuNo === this.tableInfo.list[index].skuNo;
      if (isSelectSelf) return this.$message.warning('替代商品不能选择自己');
      this.$refs.skusTable.$refs.plTable.clearSelection(); // 选择替代商品，就清空之前的表格勾选，重新进行勾选
      this.tableInfo.list[index].replaceSkuNo = data.skuNo;
      this.tableInfo.list[index].replaceProductName = data.productName;
    },
    // 获取表格信息 - 表单查询
    async getTableData () {
      this.isShowPagination = true;
      setAuthBtnId('查询');
      const data = { ...this.formData, ...this.paginationParams, ...this.waitParams };
      const loadingFn = state => { this.tableInfo.loading = state };
      const retData = await getHandlingListService(data, loadingFn);
      if (retData) {
        this.tableInfo.list = retData.results;
        this.setTotalNum(retData.totalNum);
      }
    },
    // 高级关联 - 下架 - 查询结果
    async getTableDataBySeniorDown (relParamList) {
      this.isShowPagination = false;
      setAuthBtnId('高级关联');
      const data = { relParamList, productKind: this.formData.productKind, };
      const loadingFn = state => { this.tableInfo.loading = state };
      const retData = await searchSeniorLinkedDownService(data, loadingFn);
      if (retData) {
        this.tableInfo.list = retData;
      }
    },
    // 高级关联 - 上架 - 查询结果
    async getTableDataBySeniorUp (skuNos) {
      this.isShowPagination = false;
      setAuthBtnId('高级关联');
      const data = { skuNos, productKind: this.formData.productKind, };
      const loadingFn = state => { this.tableInfo.loading = state };
      const retData = await searchSeniorLinkedUpService(data, loadingFn);
      if (retData) {
        this.tableInfo.list = retData;
      }
    },
    // 批量上架 - 提交上架商品信息
    async batchSubmitUpSkuInfo (commitReason) {
      setAuthBtnId('批量上架');
      const data = {
        skuNos: this.tableInfo.selection.map(item => item.skuNo),
        commitReason,
        productKind: this.formData.productKind,
      };
      const loadingFn = state => { this.batchUp.loading = state };
      const retStatus = await submitUpInfoService(data, loadingFn);
      if (retStatus) {
        this.$message.success('批量上架成功');
        this.resetAllState();
        this.batchUp.visible = false;
      }
    },
    // 批量下架 - 提交下架商品信息
    async batchSubmitDownSkuInfo (reasonData) {
      setAuthBtnId('批量下架');
      const downParamList = this.tableInfo.selection.map(item => ({
        skuNo: item.skuNo, replaceSkuNo: item.replaceSkuNo
      }));
      const data = {
        downParamList,
        ...reasonData,
        productKind: this.formData.productKind,
      };
      const loadingFn = state => { this.batchDown.loading = state };
      const retStatus = await submitDownInfoService(data, loadingFn);
      if (retStatus) {
        this.$message.success('批量下架成功');
        this.resetAllState();
      }
      return retStatus;
    },
    // 获取历史记录列表
    async getTableDataByHistoryRecord (skuNo) {
      const data = { skuNo };
      const loadingFn = state => { this.showList.loading = state };
      const retData = await getHistoryRecordsService(data, loadingFn);
      if (retData) {
        this.showList.list = retData;
      }
    },
    // 重置所有状态
    resetAllState () {
      this.tableInfo.list = []; // 表格清空
      this.$refs.basicForm.handleResetForm(); // 清空表单
      this.$refs.replaceSenior.resetAllData(); // 高级关联 - 下架弹框数据清空
      this.seniorLinkedUp.dataSource = []; // 高级关联 - 上架弹框数据清空
    },
    // 区域下拉集合
    async setAreaOptions () {
      const res = await manageAreaSearchService()
      const index = this.formItems.findIndex(item => item.prop == 'manageAreaId')
      if (index > -1) this.formItems[index].options = res?.retData ?? []
    },
  }
}
</script>
